<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { BasicOption } from '@vben/types';

import { computed, markRaw, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { SliderCaptcha, useVbenForm, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { Input } from 'ant-design-vue';

import { useAuthStore } from '#/store';

// import { VbenButton, VbenCheckbox } from '@vben-core/shadcn-ui';
import {
  VbenButton,
  VbenCheckbox,
} from '../../../../../../packages/@core/ui-kit/shadcn-ui/src/index';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

const MOCK_USER_OPTIONS: BasicOption[] = [
  {
    label: 'Super',
    value: 'vben',
  },
  {
    label: 'Admin',
    value: 'admin',
  },
  {
    label: 'User',
    value: 'jack',
  },
];

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenSelect',
      componentProps: {
        options: MOCK_USER_OPTIONS,
        placeholder: $t('authentication.selectAccount'),
      },
      fieldName: 'selectAccount',
      label: $t('authentication.selectAccount'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.selectAccount') })
        .optional()
        .default('vben'),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      dependencies: {
        trigger(values, form) {
          if (values.selectAccount) {
            const findUser = MOCK_USER_OPTIONS.find(
              (item) => item.value === values.selectAccount,
            );
            if (findUser) {
              form.setValues({
                password: '12345',
                username: findUser.value,
              });
            }
          }
        },
        triggerFields: ['selectAccount'],
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(5, { message: $t('authentication.passwordTip') }),
    },
    {
      component: markRaw(SliderCaptcha),
      fieldName: 'captcha',
      rules: z.boolean().refine((value) => value, {
        message: $t('authentication.verifyRequiredTip'),
      }),
    },
    {
      component: 'VbenInput',
      componentProps: {
        class: 'w-full',
        placeholder: $t('authentication.verificationCode'),
      },
      fieldName: 'code',
      label: $t('authentication.verificationCode'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.verificationCodeTip') }),
    },
    {
      component: 'VbenCheckbox',
      fieldName: 'rememberMe',
      renderComponentContent: () => ({
        default: () => $t('authentication.rememberMe'),
      }),
      rules: z.boolean().optional(),
    },
  ];
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    hideLabel: true,
  },
  handleSubmit,
  schema: formSchema.value,
  submitButtonOptions: {
    class: 'w-full',
  },
  resetButtonOptions: {
    // visible: false,
    class: 'hidden',
  },
  submitOnEnter: true,
});

const REMEMBER_ME_KEY = `REMEMBER_ME_USERNAME_${location.hostname}`;

const localUsername = localStorage.getItem(REMEMBER_ME_KEY) || '';

const rememberMe = ref(!!localUsername);

const router = useRouter();
function handleGo(path: string) {
  router.push(path);
}

async function handleSubmit() {
  const values = await formApi.getValues();
  formApi.setFieldValue('rememberMe', rememberMe.value);
  // console.log(values, rememberMe.value);
  localStorage.setItem(
    REMEMBER_ME_KEY,
    rememberMe.value ? values.username : '',
  );
  authStore.authLogin(values);
}

onMounted(() => {
  authStore.getCaptcha();
  if (localUsername) {
    formApi.setFieldValue('username', localUsername);
  }
  watch(
    () => authStore.captcha.uuid,
    (newUuid) => {
      if (newUuid) {
        formApi.setFieldValue('uuid', newUuid);
      }
    },
  );
});
</script>

<template>
  <!-- <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="authStore.authLogin"
  /> -->
  <div>
    <Form>
      <template #code="slotProps">
        <Input
          class="mr-2 h-10"
          v-bind="slotProps"
          @input="slotProps['onUpdate:modelValue']($event.target.value)"
        />
        <img
          :src="authStore.captcha.img"
          alt=""
          @click="authStore.getCaptcha"
          class="h-10"
        />
      </template>
      <template #rememberMe>
        <div class="flex w-full justify-between">
          <div class="flex-center">
            <VbenCheckbox v-model="rememberMe" name="rememberMe">
              {{ $t('authentication.rememberMe') }}
            </VbenCheckbox>
          </div>

          <span
            class="vben-link text-sm font-normal"
            @click="handleGo('/auth/forget-password')"
          >
            {{ $t('authentication.forgetPassword') }}
          </span>
        </div>
      </template>
    </Form>

    <div class="mb-2 mt-4 flex items-center justify-between">
      <VbenButton
        class="w-1/2"
        variant="outline"
        @click="handleGo('/auth/code-login')"
      >
        {{ $t('authentication.mobileLogin') }}
      </VbenButton>
      <VbenButton
        class="ml-4 w-1/2"
        variant="outline"
        @click="handleGo('/auth/qrcode-login')"
      >
        {{ $t('authentication.qrcodeLogin') }}
      </VbenButton>
    </div>

    <slot name="to-register">
      <div class="mt-3 text-center text-sm">
        {{ $t('authentication.accountTip') }}
        <span
          class="vben-link text-sm font-normal"
          @click="handleGo('/auth/register')"
        >
          {{ $t('authentication.createAccount') }}
        </span>
      </div>
    </slot>
  </div>
</template>
